package com.hzhc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.YytNotice;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.mapper.YytNoticeMapper;
import com.hzhc.service.YytNoticeService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.YytNoticeVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 * 新闻公告 服务实现类
 * </p>
 *
 * @author zhoumx
 * @since 2024-04-12
 */
@Service
@RequiredArgsConstructor
public class YytNoticeServiceImpl extends ServiceImpl<YytNoticeMapper, YytNotice> implements YytNoticeService {

    @Value("${file.yypUploadFolder}")
    private String yypictureFileAccessPath;
    @Value("${picture}")
    private String picturefolder;
    private YytNoticeMapper yytNoticeMapper;


    @Override
    public List<YytNoticeVo> getYytNoticeVoList(Page<YytNoticeVo> page, YytNoticeVo vo) {
        IPage<YytNoticeVo> iPage= baseMapper.getYytNoticePage(page,vo);
        return iPage.getRecords();
    }

    @Override
    public List<YytNoticeVo> getYzsYytNoticeVoList(YytNoticeVo yytNoticeVo) {
        return baseMapper.getYzsYytNoticeList(yytNoticeVo);
    }

    @Override
    public Boolean checkYytNoticeTitle(String field, String fieldStr, Long id) {
        QueryWrapper<YytNotice> queryWrapper=new QueryWrapper<YytNotice>();
        queryWrapper.eq(field,fieldStr);
        if(id != null){
            queryWrapper.ne("id",id);
        }
        List<YytNotice> list = baseMapper.selectList(queryWrapper);
        return !list.isEmpty();
    }

    @Override
    public Boolean addYytNotice(YytNotice yytNotice) {
        String workNotice = StringEscapeUtils.unescapeHtml4(yytNotice.getWorkNotice());
        yytNotice.setWorkNotice(workNotice);
        yytNotice.setCreateTime(LocalDateTime.now());
        yytNotice.setUpdateTime(LocalDateTime.now());
        return save(yytNotice);
    }

    @Override
    public Boolean updateYytNotice(YytNotice yytNotice) {
        String workNotice = StringEscapeUtils.unescapeHtml4(yytNotice.getWorkNotice());
        yytNotice.setWorkNotice(workNotice);
        return updateById(yytNotice);
    }

    @Override
    public Boolean updateYytNoticeTop(YytNotice yytNotice) {
        YytNotice notice=getById(yytNotice.getId());
        notice.setIstop(yytNotice.getIstop());
        return updateById(yytNotice);
    }

    @Override
    public Boolean delYytNotice(Long id) {
        return removeById(id);
    }

    @Override
    public ResultUtil<String> upfile(MultipartFile file, String yypUploadFolder, String yypAccessPath) {
        if (file!= null) {
            String pathUrl =   saveFiles(file, yypUploadFolder, yypAccessPath);
            return ResultUtil.build(pathUrl, ResultUtilCodeEnum.SUCCESS);
        }
        return ResultUtil.fail();
    }


    public String saveFiles( MultipartFile files, String upfolder, String accessPath) {
        //设置日期格式
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //当地日期转换
        String dayFormat = LocalDate.now().format(formatters);
        //创建新文件：通过路径和时间
        File folder = new File(upfolder + File.separator + dayFormat);
        //文件是否存在，不存在进行创建。
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //获取文件名
        String regEx1 = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        String fileName = files.getOriginalFilename();
        String urlName = (LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + Pattern.compile(regEx1).matcher(fileName).replaceAll("").trim());
        //设置路径
        String path = folder + File.separator;
        File file = getFileByName(1, path, urlName);
        String uploadedFilePath = null; // 保存上传文件的访问路径
        try {
            // 上传文件到服务器
            files.transferTo(file);
            //YytNotice yytNotice = getById(id);
            // 构建文件的访问路径
//            uploadedFilePath = accessPath.substring(0, accessPath.lastIndexOf("/")) + "/" + path + "/" + file.getName();
//            uploadedFilePath = picturefolder  + yypictureFileAccessPath + file.getName();
            uploadedFilePath = picturefolder+File.separator + dayFormat+File.separator +urlName;
//            yytNotice.setAvatarUrl(uploadedFilePath);
//            boolean b = updateById(yytNotice);
            // 返回上传文件的访问路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadedFilePath;
    }

    private File getFileByName(int count, String path, String fileName) {
        File file = new File(path + fileName);
        if (file.exists()) {
            // 文件名已存在
            String prefix = fileName.substring(0, fileName.lastIndexOf(".")) + "(" + count + ")";
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            file = getFileByName(count + 1, path, prefix + suffixName);
        }
        return file;
    }

}


